package cn.lby.tp.downloadtest.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.lby.tp.downloadtest.R;
import cn.lby.tp.downloadtest.interfaces.MyOnLongClickListener;
import down.DownLoaderHelper;
import down.DownLoaderManger;
import down.Utils;
import download_temp.FileInfo;
import download_temp.view.NumberProgressBar;


public class DownDoneFragment extends Fragment {
    private View view;

    public DownDoneFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_down_done, container, false);
            r2 = view.findViewById(R.id.r2);
            r2.setItemAnimator(null);
            LinearLayoutManager layout = new LinearLayoutManager(context, RecyclerView.VERTICAL, false);
            r2.setLayoutManager(layout);
            r2.setAdapter(adapter);
            r2.setLongClickable(true);
        }
        return view;
    }

    // 全选
    public void qx() {
        adapter.setSelect(true);
        adapter.All();
    }

    // 全不选
    public void qbx() {
        adapter.setSelect(false);
        adapter.AllNot();
    }


    // 处理多选数据
    @SuppressLint("DefaultLocale")
    public void commit() {
        // 记录选择的数据
        List<FileInfo> tempList = new ArrayList<>();
        Map<Integer, Boolean> map = adapter.getMap();
        for (int i = 0; i < fileInfoList.size(); i++) {
            if (map.get(i)) {
                tempList.add(fileInfoList.get(i));
            }
        }
        if (tempList.size() == 0) {
            Toast.makeText(context, "请先选择", Toast.LENGTH_SHORT).show();
            return;
        }
        for (FileInfo fileInfo : tempList) {
            File file = new File(Utils.PARENT_PATH, fileInfo.getFileName());
            Utils.deleteFiles(file, null, false);
            downLoaderManger.delete(fileInfo);
            // 删除后更新
            fileInfoList.remove(fileInfo);
            adapter.notifyAdapter(fileInfoList, false);
        }
        Toast.makeText(context, String.format("本次删除%d个文件", tempList.size()), Toast.LENGTH_SHORT).show();
    }


    private Context context;
    private RecyclerView r2;
    private MyRecyclerView adapter;
    private List<FileInfo> fileInfoList;
    private DownLoaderManger downLoaderManger;

    // 接口实例
    private Callbacks callbacks;

    // Fragment内部回调接口
    public interface Callbacks {
        void onItemSelected();
    }

    public MyRecyclerView getAdapter() {
        return adapter;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (!(context instanceof Callbacks)) {
            // 如果 Activity 没有实现内部回调接口，抛出异常
            throw new IllegalStateException("必须实现Callbacks接口");
        }
        callbacks = (Callbacks) context;
        this.context = context;
    }


    @SuppressLint("NotifyDataSetChanged")
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        downLoaderManger = DownLoaderManger.getInstance(new DownLoaderHelper(context));
        // 获取所有下载中的任务
        fileInfoList = downLoaderManger.getAllDownloaded();

        adapter = new MyRecyclerView(context, fileInfoList);

        adapter.setListener(new MyRecyclerView.MyOnclickListener() {
            @Override
            public void click(int position, MyRecyclerView.MyRecyclerViewHandler handler) {
                if (adapter.isSelect) {
                    handler.setCbox();
                    return;
                }
                downHandler(position);
            }
        });


                /*
                FileInfo fileInfo = fileInfoList.get(position);
                File file = new File(Utils.PARENT_PATH, fileInfo.getFileName());
                Utils.deleteFiles(file, null, false);
                downLoaderManger.delete(fileInfo);

                // 删除后更新
                int len = fileInfoList.size();
                fileInfoList.remove(fileInfo);
                adapter.setInfoList(fileInfoList);
                adapter.notifyItemRangeRemoved(0, len);
                Toast.makeText(context, "任务已删除", Toast.LENGTH_SHORT).show();

                 */

        // 长按
        adapter.setLongClickListener((position, handler) -> {
            itemLongClick(handler);
            callbacks.onItemSelected();
        });

    }

    private void itemLongClick(MyRecyclerView.MyRecyclerViewHandler handler) {
        handler.cbox.setChecked(true);
        adapter.showSelect();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void recyclerViewNotify() {
        if (fileInfoList != null) {
            fileInfoList = downLoaderManger.getAllDownloaded();
            adapter.notifyAdapter(fileInfoList, false);
        }
    }

    // 列表适配器
    public static class MyRecyclerView extends RecyclerView.Adapter<MyRecyclerView.MyRecyclerViewHandler> {
        // Context
        private Context context;
        // 数据列表
        private List<FileInfo> infoList;
        // 多选
        private HashMap<Integer, Boolean> maps = new HashMap<>();

        private boolean isSelect;

        public boolean isSelect() {
            return isSelect;
        }

        public void setSelect(boolean select) {
            isSelect = select;
        }

        public MyRecyclerView(Context context, List<FileInfo> fileInfoList1) {
            this.context = context;
            this.infoList = fileInfoList1;
            initMap();
        }

        // 每一次进入列表页面  都是未选中状态
        private void initMap() {
            for (int i = 0; i < infoList.size(); i++) {
                maps.put(i, false);
            }
        }

        @SuppressLint("NotifyDataSetChanged")
        public void showSelect() {
            this.isSelect = true;
            notifyDataSetChanged();
        }

        @SuppressLint("NotifyDataSetChanged")
        public void notifyAdapter(List<FileInfo> list, boolean isAdd) {
            if (!isAdd) {
                this.infoList = list;
            } else {
                this.infoList.addAll(list);
            }
            notifyDataSetChanged();

        }

        @NonNull
        @Override
        public MyRecyclerViewHandler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.down_item, parent, false);
            return new MyRecyclerViewHandler(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyRecyclerViewHandler holder, int position) {
            FileInfo item = infoList.get(position);
            holder.title.setText(item.getFileName());
            float progress = (float) item.getFinished() / item.getLength() * 100;
            holder.pb.setProgress((int) progress);
            if (Utils.isDownLoaded(item)) {

                if (isSelect) {
                    holder.cbox.setVisibility(View.VISIBLE);
                    isSelect = true;
                } else {
                    holder.cbox.setVisibility(View.GONE);
                    isSelect = false;
                }


                String fileSize = Utils.formatFileSize((long) item.getLength());
                holder.state.setText(fileSize);
                holder.pb.setVisibility(View.GONE);

                // CheBox 选中后
                holder.cbox.setOnCheckedChangeListener((compoundButton, b) -> {
                    maps.put(position, b);
                });

                Boolean checked = maps.get(position);
                if (checked == null) {
                    maps.put(position, false);
                }
                //没有设置tag之前会有item重复选框出现，设置tag之后，此问题解决
                holder.cbox.setChecked(checked);
            }
        }


        @Override
        public int getItemCount() {
            return infoList == null ? 0 : infoList.size();
        }


        interface MyOnclickListener {
            void click(int position, MyRecyclerViewHandler handler);
        }


        private MyOnclickListener onclickListener;
        private MyOnLongClickListener<MyRecyclerViewHandler> longClickListener;

        public void setListener(MyOnclickListener listener) {
            this.onclickListener = listener;
        }

        public void setLongClickListener(MyOnLongClickListener<MyRecyclerViewHandler> longClickListener) {
            this.longClickListener = longClickListener;
        }

        //获取最终的map存储数据
        public Map<Integer, Boolean> getMap() {
            return maps;
        }

        //全选方法
        @SuppressLint("NotifyDataSetChanged")
        public void All() {
            Set<Map.Entry<Integer, Boolean>> entries = maps.entrySet();
            boolean shouldall = false;
            for (Map.Entry<Integer, Boolean> entry : entries) {
                Boolean value = entry.getValue();
                if (!value) {
                    shouldall = true;
                    break;
                }
            }
            for (Map.Entry<Integer, Boolean> entry : entries) {
                entry.setValue(shouldall);
            }
            notifyDataSetChanged();
        }

        @SuppressLint("NotifyDataSetChanged")
        public void AllNot() {
            Set<Map.Entry<Integer, Boolean>> entries = maps.entrySet();
            for (Map.Entry<Integer, Boolean> entry : entries) {
                entry.setValue(false);
            }
            notifyDataSetChanged();
        }

        // 反选
        @SuppressLint("NotifyDataSetChanged")
        public void neverall() {
            Set<Map.Entry<Integer, Boolean>> entries = maps.entrySet();
            for (Map.Entry<Integer, Boolean> entry : entries) {
                entry.setValue(!entry.getValue());
            }
            notifyDataSetChanged();
        }

        //多选
        public void MultiSelection(int position) {
            //对当前状态取反
            if (maps.get(position)) {
                maps.put(position, false);
            } else {
                maps.put(position, true);
            }
            notifyItemChanged(position);
        }


        public class MyRecyclerViewHandler extends RecyclerView.ViewHolder {
            @BindView(R.id.name)
            TextView title;
            @BindView(R.id.state)
            TextView state;
            @BindView(R.id.pb)
            NumberProgressBar pb;
            @BindView(R.id.cbox)
            CheckBox cbox;

            public MyRecyclerViewHandler(@NonNull View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                itemView.setOnClickListener(v -> {
                    if (infoList != null) {
                        onclickListener.click(getPosition(), this);

                    }
                });
                itemView.setOnLongClickListener(v -> {
                    longClickListener.longClick(getPosition(), this);
                    return true;
                });
            }

            public void setCbox() {
                cbox.setChecked(!cbox.isChecked());
            }

        }
    }

    private void downHandler(int position) {
//         FileInfo itemInfo = fileInfoList.get(position);
        Toast.makeText(context, "该资源已经下载完成", Toast.LENGTH_SHORT).show();
    }
}

